package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.system.domain.DeviceAlarm;
import org.dromara.system.service.IDeviceAlarmService;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.VariableAssociationParamBo;
import org.dromara.system.domain.vo.VariableAssociationParamVo;
import org.dromara.system.domain.VariableAssociationParam;
import org.dromara.system.mapper.VariableAssociationParamMapper;
import org.dromara.system.service.IVariableAssociationParamService;

import java.math.BigDecimal;
import java.util.*;

/**
 * 变量参数关联Service业务层处理
 *
 * @author Lion Li
 * @date 2024-10-21
 */
@RequiredArgsConstructor
@Service
public class VariableAssociationParamServiceImpl implements IVariableAssociationParamService {

    private final VariableAssociationParamMapper baseMapper;

    private final IDeviceAlarmService deviceAlarmService;
    /**
     * 查询变量参数关联
     *
     * @param id 主键
     * @return 变量参数关联
     */
    @Override
    public VariableAssociationParamVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询变量参数关联列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 变量参数关联分页列表
     */
    @Override
    public TableDataInfo<VariableAssociationParamVo> queryPageList(VariableAssociationParamBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<VariableAssociationParam> lqw = buildQueryWrapper(bo);
        Page<VariableAssociationParamVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的变量参数关联列表
     *
     * @param bo 查询条件
     * @return 变量参数关联列表
     */
    @Override
    public List<VariableAssociationParamVo> queryList(VariableAssociationParamBo bo) {
        LambdaQueryWrapper<VariableAssociationParam> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<VariableAssociationParam> buildQueryWrapper(VariableAssociationParamBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<VariableAssociationParam> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getVariableId() != null, VariableAssociationParam::getVariableId, bo.getVariableId());
        lqw.eq(bo.getUpThreshold() != null, VariableAssociationParam::getUpThreshold, bo.getUpThreshold());
        lqw.eq(StringUtils.isNotBlank(bo.getUpThresholdDesc()), VariableAssociationParam::getUpThresholdDesc, bo.getUpThresholdDesc());
        lqw.eq(bo.getDownThreshold() != null, VariableAssociationParam::getDownThreshold, bo.getDownThreshold());
        lqw.eq(StringUtils.isNotBlank(bo.getDownThresholdDesc()), VariableAssociationParam::getDownThresholdDesc, bo.getDownThresholdDesc());
        lqw.eq(bo.getIdentifier() != null, VariableAssociationParam::getIdentifier, bo.getIdentifier());
        lqw.eq(bo.getMultiple() != null, VariableAssociationParam::getMultiple, bo.getMultiple());
        lqw.eq(bo.getLevel() != null, VariableAssociationParam::getLevel, bo.getLevel());
        return lqw;
    }

    /**
     * 新增变量参数关联
     *
     * @param bo 变量参数关联
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(VariableAssociationParamBo bo) {
        VariableAssociationParam add = MapstructUtils.convert(bo, VariableAssociationParam.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改变量参数关联
     *
     * @param bo 变量参数关联
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(VariableAssociationParamBo bo, Long id) {
        //根据id和level判断是否存在该条数据 如果不存在则添加 存在则更新
        VariableAssociationParam variableAssociationParams = baseMapper.selectOne(Wrappers.<VariableAssociationParam>lambdaQuery().eq(VariableAssociationParam::getId, id).eq(VariableAssociationParam::getLevel, bo.getLevel()));
        if (variableAssociationParams == null) {
            //不存在则添加
            VariableAssociationParam add = MapstructUtils.convert(bo, VariableAssociationParam.class);
            return baseMapper.insert(add) > 0;
        } else {
            validEntityBeforeUpdate(bo, id);
            validEntityBeforeAlarmStatus(variableAssociationParams);
            //存在 先判断修改的值是否与数据库中存在 我的意思是 假如传入upThreshold的值为1 但是该变量的等级2的值也是1 则不能存入
            variableAssociationParams.setDownThreshold(bo.getDownThreshold());
            variableAssociationParams.setDownThresholdDesc(bo.getDownThresholdDesc());
            variableAssociationParams.setUpThreshold(bo.getUpThreshold());
            variableAssociationParams.setUpThresholdDesc(bo.getUpThresholdDesc());
            variableAssociationParams.setStatusValue(bo.getStatusValue());
            variableAssociationParams.setStatusValueDesc(bo.getStatusValueDesc());
            return baseMapper.updateById(variableAssociationParams) > 0;

        }
    }

    private void validEntityBeforeAlarmStatus(VariableAssociationParam variableAssociationParams) {
        DeviceAlarm deviceAlarm = deviceAlarmService.getDeviceAlarm(variableAssociationParams.getVariableId(), variableAssociationParams.getLevel());
        if (deviceAlarm!=null){
            deviceAlarm.setStatus(1L);
            deviceAlarm.setFinishTime(new Date());
            deviceAlarmService.update(deviceAlarm);
        }
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(VariableAssociationParam entity) {


        //TODO 做一些数据校验,如唯一约束
    }

    private void validEntityBeforeUpdate(VariableAssociationParamBo bo,Long id) {
        // 检查upThreshold是否已经存在于其他level的记录中
        VariableAssociationParam existingUpThreshold = baseMapper.selectOne(Wrappers.<VariableAssociationParam>lambdaQuery()
            .ne(VariableAssociationParam::getId, id) // 排除当前id
            .eq(VariableAssociationParam::getUpThreshold, bo.getUpThreshold()));
        if (existingUpThreshold != null){
            throw new ServiceException("已存在相同上线阀值");
        }
        // 检查downThreshold是否已经存在于其他level的记录中
        VariableAssociationParam existingDownThreshold = baseMapper.selectOne(Wrappers.<VariableAssociationParam>lambdaQuery()
            .ne(VariableAssociationParam::getId, id) // 排除当前id
            .eq(VariableAssociationParam::getDownThreshold, bo.getDownThreshold()));
        if (existingDownThreshold != null){
            throw new ServiceException("已存在相同下线阀值");
        }
        // 检查statusValue是否已经存在于其他level的记录中
        VariableAssociationParam existingStatusValue = baseMapper.selectOne(Wrappers.<VariableAssociationParam>lambdaQuery()
            .ne(VariableAssociationParam::getId, id) // 排除当前id
            .eq(VariableAssociationParam::getStatusValue, bo.getStatusValue()));

        if (existingStatusValue != null) {
            // 如果upThreshold、downThreshold或statusValue已经存在，则返回false或抛出异常
            throw new ServiceException("参数值已存在");
        }


        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除变量参数关联信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<VariableAssociationParam> getAssociationParam(Long id) {
        LambdaQueryWrapper<VariableAssociationParam> lqw = Wrappers.lambdaQuery();
        lqw.eq(id != null, VariableAssociationParam::getVariableId, id);
        List<VariableAssociationParam> variableAssociationParams = baseMapper.selectList(lqw);
        if (CollectionUtils.isEmpty(variableAssociationParams)) {
            //每个变量插入3条数据到变量参数关联表 level分别是1,2,3 其他值都默认
            createAndInsertParams(id);
            variableAssociationParams = baseMapper.selectList(lqw);
        }
        return variableAssociationParams;
    }

    private void createAndInsertParams(Long id) {
        List<VariableAssociationParam> variableAssociationParamList = new ArrayList<>();

        for (int i = 1; i <= 3; i++) {
            VariableAssociationParam param = new VariableAssociationParam();
            param.setVariableId(id);
            param.setMultiple(0L);
            param.setIdentifier((long) i);
            param.setLevel((long) i);
            param.setDownThreshold(null);
            param.setUpThreshold(null);
            param.setDownThresholdDesc("");
            param.setUpThresholdDesc("");
            param.setStatusValue(null);
            param.setStatusValueDesc("");
            variableAssociationParamList.add(param);
        }

        baseMapper.insertBatch(variableAssociationParamList);
    }

}

